﻿using Microsoft.Maui.Storage;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static HalkSee.ShowRecord;

namespace HalkSee.Helper
{
    public class FileHelper
    {
        public static void WriteFile(string dir, string fileName, byte[] data)
        {
            var fullPath = Path.Combine(dir, fileName);
            if(!File.Exists(fullPath))
                File.WriteAllBytes(fullPath, data);
        }

        public static string[] GetFiles(string dir)
        {
            var files = Directory.GetFiles(dir);
            if (files == null || files.Length == 0)
            {
                return Array.Empty<string>();
            }
            else
            {
                return files.Select((m, i) => Path.GetFileName(m))
                                  .Where(m => m != "hw_cached_resid.list" && m != "aware_learning_data")
                                  .OrderBy(m => m)
                                  .ToArray();
            }
        }

        public static byte[] GetFile(string dir, string fileName)
        {
            var fullPath = Path.Combine(dir, fileName);
            if (!File.Exists(fullPath))
                return Array.Empty<byte>();
            else
                return File.ReadAllBytes(fullPath);
        }

        public static void DeleteFiles(string dir, string[] files)
        {
            foreach(var file in files)
            {
                if (File.Exists(file))
                    File.Delete(file);
            }
        }

        public static void ClearDir(string dir)
        {
            var files = GetFiles(dir);
            if (files.Length > 0)
            {
                foreach (var file in files)
                {
                    if (File.Exists(file))
                        File.Delete(file);
                }
            }
        }

        public static bool Exists(string dir, string fileName) => File.Exists(Path.Combine(dir, fileName));
    }
}
